---
title: Filter
js: examples/filter.js
---

<p class="flex justify-between">
    <a href="../13_drag_outside/">&laquo; Example 13</a>
</p>

<h1>Example 14 - filter</h1>

<div class="pb-6">
    <input id="search-term" class="shadow-sm border px-4 py-1 focus:ring-indigo-500 focus:border-indigo-500 border-gray-300 rounded-md mr-4" autofocus></input>
    <button id="search" class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Search</button>
</div>
<div id="tree1" class="not-prose"></div>

<h3>javascript</h3>

{% highlight js %}
const $tree = $("#tree1");

let foundMatch = false;

$tree.tree({
    autoOpen: false,
    data: ExampleData.exampleData,
    useContextMenu: false,
    onCreateLi: (node, $el) => {
        if (foundMatch && !node.openForMatch && !node.parent.matches) {
            $el.addClass("hidden-node");
        }

        if (node.matches) {
            $el.addClass("highlight-node");
        }
    },
});

$("#search").on("click", () => {
    const searchTerm = $("#search-term").val().toLowerCase();
    const tree = $tree.tree("getTree");

    if (!searchTerm) {
        foundMatch = false;

        tree.iterate((node) => {
            node['openForMatch'] = false;
            node["matches"] = false;
            return true;
        });

        $tree.tree("refresh");
        return;
    }

    foundMatch = false;

    tree.iterate((node) => {
        const matches = node.name.toLowerCase().includes(searchTerm);
        node["openForMatch"] = matches;
        node["matches"] = matches;

        if (matches) {
            foundMatch = true;

            if (node.isFolder()) {
                node.is_open = true;
            }

            let parent = node.parent;
            while (parent) {
                parent["openForMatch"] = true;
                parent.is_open = true;
                parent = parent.parent;
            }
        }

        return true;
    });

    $tree.tree("refresh");
});
{% endhighlight %}

<h3>html</h3>

{% highlight html %}
<div">
    <input id="search-term" autofocus></input>
    <button id="search">Search</button>
</div>
<div id="tree1"></div>
{% endhighlight %}

<h3>css</h3>

{% highlight css %}
.hidden-node {
    display: none;
}

.highlight-node > .jqtree-element > .jqtree-title {
    font-weight: bold;
}

#search-term {
    margin-bottom: 16px;
    margin-right: 8px;
}
{% endhighlight %}
